<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>选项管理 - 员工信息管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
        }

        /* 头部样式 */
        .header {
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 15px 30px;
            margin-bottom: 20px;
        }

        .header-content {
            max-width: 1400px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
        }

        .header h1 {
            color: #409eff;
            font-size: 24px;
            flex: 0 0 auto;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 15px;
            flex: 0 0 auto;
        }

        .nav-menu {
            display: flex;
            gap: 10px;
            flex: 1;
            justify-content: center;
        }

        .nav-btn {
            padding: 8px 15px;
            background-color: #ecf5ff;
            color: #409eff;
            border: 1px solid #b3d8ff;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.3s;
        }

        .nav-btn:hover {
            background-color: #409eff;
            color: #fff;
        }

        .nav-btn.active {
            background-color: #409eff;
            color: #fff;
        }

        /* 容器样式 */
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .card {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        .card-title {
            font-size: 18px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #409eff;
        }

        /* 查询表单样式 */
        .search-form {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
            margin-bottom: 15px;
        }

        .form-item {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .form-item label {
            font-size: 14px;
            color: #606266;
        }

        .form-item input, .form-item select {
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            min-width: 180px;
        }

        .form-item input:focus, .form-item select:focus {
            outline: none;
            border-color: #409eff;
        }

        /* 按钮样式 */
        .btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .btn-primary {
            background-color: #409eff;
            color: #fff;
        }

        .btn-primary:hover {
            background-color: #66b1ff;
        }

        .btn-success {
            background-color: #67c23a;
            color: #fff;
        }

        .btn-success:hover {
            background-color: #85ce61;
        }

        .btn-danger {
            background-color: #f56c6c;
            color: #fff;
        }

        .btn-danger:hover {
            background-color: #f78989;
        }

        .btn-default {
            background-color: #fff;
            color: #606266;
            border: 1px solid #dcdfe6;
        }

        .btn-default:hover {
            background-color: #ecf5ff;
            border-color: #409eff;
            color: #409eff;
        }

        .btn-warning {
            background-color: #e6a23c;
            color: #fff;
        }

        .btn-warning:hover {
            background-color: #ebb563;
        }

        /* 工具栏 */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .toolbar-left {
            display: flex;
            gap: 10px;
        }

        /* 表格样式 */
        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
        }

        table thead {
            background-color: #f5f7fa;
        }

        table th {
            padding: 12px;
            text-align: left;
            font-weight: 600;
            color: #303133;
            border-bottom: 1px solid #ebeef5;
        }

        table td {
            padding: 12px;
            border-bottom: 1px solid #ebeef5;
            color: #606266;
        }

        table tbody tr:hover {
            background-color: #f5f7fa;
        }

        table th input[type="checkbox"],
        table td input[type="checkbox"] {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }

        /* 操作按钮 */
        .action-btn {
            padding: 4px 8px;
            font-size: 12px;
            margin-right: 5px;
        }

        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }

        .pagination button {
            padding: 6px 12px;
            border: 1px solid #dcdfe6;
            background-color: #fff;
            color: #606266;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .pagination button:hover:not(:disabled) {
            color: #409eff;
            border-color: #409eff;
        }

        .pagination button:disabled {
            cursor: not-allowed;
            opacity: 0.5;
        }

        .pagination button.active {
            background-color: #409eff;
            color: #fff;
            border-color: #409eff;
        }

        .pagination-info {
            font-size: 14px;
            color: #606266;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            animation: fadeIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal.show {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: #fff;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            animation: slideDown 0.3s;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            color: #303133;
            font-size: 18px;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            color: #909399;
            cursor: pointer;
            line-height: 1;
        }

        .close-btn:hover {
            color: #f56c6c;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 20px;
            border-top: 1px solid #ebeef5;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            color: #606266;
            font-weight: 500;
        }

        .form-group label .required {
            color: #f56c6c;
            margin-right: 4px;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            font-family: inherit;
        }

        .form-group textarea {
            min-height: 80px;
            resize: vertical;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #409eff;
        }

        .form-group .error {
            color: #f56c6c;
            font-size: 12px;
            margin-top: 5px;
        }

        /* 空数据提示 */
        .empty-data {
            text-align: center;
            padding: 40px;
            color: #909399;
        }

        .empty-data p {
            font-size: 14px;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <!-- 头部 -->
    <div class="header">
        <div class="header-content">
            <h1>员工信息管理系统</h1>
            <div class="nav-menu">
                <a href="employee.html" class="nav-btn">员工管理</a>
                <a href="option.html" class="nav-btn active">选项管理</a>
            </div>
            <div class="header-right">
                <!-- 未登录状态 -->
                <div id="notLoggedIn" style="display: none;">
                    <span style="color: #909399;">未登录</span>
                    <button class="btn btn-primary" onclick="goToLogin()">点击登录</button>
                </div>
                <!-- 已登录状态 -->
                <div id="loggedIn" style="display: none;">
                    <span id="username">欢迎您</span>
                    <button class="btn btn-default" onclick="logout()">退出登录</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 主容器 -->
    <div class="container">
        <!-- 查询区域 -->
        <div class="card">
            <div class="card-title">查询条件</div>
            <form class="search-form" id="searchForm">
                <div class="form-item">
                    <label>名称</label>
                    <input type="text" id="searchName" placeholder="请输入名称">
                </div>
                <div class="form-item">
                    <label>范畴</label>
                    <input type="text" id="searchCategory" placeholder="请输入范畴">
                </div>
                <div class="form-item">
                    <label>&nbsp;</label>
                    <button type="button" class="btn btn-primary" onclick="search()">查询</button>
                    <button type="button" class="btn btn-default" onclick="resetSearch()">重置</button>
                </div>
            </form>
        </div>

        <!-- 数据表格区域 -->
        <div class="card">
            <div class="toolbar">
                <div class="toolbar-left">
                    <button class="btn btn-success" onclick="showAddModal()">新增选项</button>
                    <button class="btn btn-danger" onclick="deleteBatch()">批量删除</button>
                </div>
                <div class="pagination-info">
                    共 <span id="totalCount">0</span> 条记录
                </div>
            </div>

            <div class="table-container">
                <table id="dataTable">
                    <thead>
                        <tr>
                            <th width="50">
                                <input type="checkbox" id="checkAll" onchange="toggleCheckAll()">
                            </th>
                            <th width="80">序号</th>
                            <th>名称</th>
                            <th>范畴</th>
                            <th>值</th>
                            <th>备注</th>
                            <th width="200">操作</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- 数据行将由JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <div class="pagination" id="pagination">
                <!-- 分页按钮将由JavaScript动态生成 -->
            </div>
        </div>
    </div>

    <!-- 新增/编辑模态框 -->
    <div class="modal" id="optionModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">新增选项</h3>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <div class="modal-body">
                <form id="optionForm">
                    <input type="hidden" id="optionId">
                    
                    <div class="form-group">
                        <label><span class="required">*</span>名称</label>
                        <input type="text" id="name" placeholder="请输入名称" required>
                    </div>

                    <div class="form-group">
                        <label><span class="required">*</span>范畴</label>
                        <input type="text" id="category" placeholder="请输入范畴（如：岗位类型、性别等）" required>
                    </div>

                    <div class="form-group">
                        <label><span class="required">*</span>值</label>
                        <input type="text" id="value" placeholder="请输入值" required>
                    </div>

                    <div class="form-group">
                        <label>备注</label>
                        <textarea id="remark" placeholder="请输入备注"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" onclick="closeModal()">取消</button>
                <button class="btn btn-primary" onclick="saveOption()">保存</button>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;
        let isEditMode = false;
        let isLoggedIn = false; // 登录状态标记

        // 检查登录状态
        function checkLogin() {
            if (!isLoggedIn) {
                alert('您尚未登录，请先登录！');
                window.location.href = '../login.html';
                return false;
            }
            return true;
        }

        // 跳转到登录页面
        function goToLogin() {
            window.location.href = '../login.html';
        }

        // 更新用户界面显示
        function updateUIForLoginStatus(loggedIn, username) {
            if (loggedIn) {
                // 已登录
                document.getElementById('notLoggedIn').style.display = 'none';
                document.getElementById('loggedIn').style.display = 'flex';
                document.getElementById('username').textContent = '欢迎，' + (username || 'admin');
            } else {
                // 未登录
                document.getElementById('notLoggedIn').style.display = 'flex';
                document.getElementById('loggedIn').style.display = 'none';
            }
        }

        // 页面加载完成后执行
        window.onload = function() {
            // 检查登录状态
            fetch('../option/list?pageNum=1&pageSize=1', {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (response.status === 401) {
                    // 未登录
                    isLoggedIn = false;
                    updateUIForLoginStatus(false);
                } else if (response.ok) {
                    // 已登录
                    isLoggedIn = true;
                    // 从session获取用户名
                    const username = sessionStorage.getItem('username') || 'admin';
                    updateUIForLoginStatus(true, username);
                    // 加载数据
                    loadData();
                }
                return response.ok ? response.json() : null;
            })
            .catch(error => {
                console.error('登录状态检查失败:', error);
                isLoggedIn = false;
                updateUIForLoginStatus(false);
            });
        };

        // 加载数据
        function loadData() {
            const name = document.getElementById('searchName').value;
            const category = document.getElementById('searchCategory').value;

            const params = new URLSearchParams({
                pageNum: currentPage,
                pageSize: pageSize,
                name: name || '',
                category: category || ''
            });

            fetch(`../option/list?${params}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        renderTable(result.data);
                        renderPagination(result.data);
                    } else {
                        alert('查询失败：' + result.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('系统错误，请稍后重试');
                });
        }

        // 渲染表格
        function renderTable(data) {
            const tbody = document.getElementById('tableBody');
            const list = data.list || [];
            
            document.getElementById('totalCount').textContent = data.total || 0;

            if (list.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" class="empty-data">
                            <p>暂无数据</p>
                        </td>
                    </tr>
                `;
                return;
            }

            let html = '';
            list.forEach((item, index) => {
                const rowNum = (currentPage - 1) * pageSize + index + 1;
                html += `
                    <tr>
                        <td><input type="checkbox" class="row-check" value="${item.id}"></td>
                        <td>${rowNum}</td>
                        <td>${escapeHtml(item.name)}</td>
                        <td>${escapeHtml(item.category)}</td>
                        <td>${escapeHtml(item.value)}</td>
                        <td>${escapeHtml(item.remark || '-')}</td>
                        <td>
                            <button class="btn btn-primary action-btn" onclick="showEditModal('${item.id}')">编辑</button>
                            <button class="btn btn-danger action-btn" onclick="deleteOption('${item.id}')">删除</button>
                        </td>
                    </tr>
                `;
            });
            tbody.innerHTML = html;

            // 重置全选checkbox
            document.getElementById('checkAll').checked = false;
        }

        // 渲染分页
        function renderPagination(data) {
            const pagination = document.getElementById('pagination');
            const total = data.total || 0;
            totalPages = Math.ceil(total / pageSize);

            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }

            let html = `
                <button onclick="goToPage(1)" ${currentPage === 1 ? 'disabled' : ''}>首页</button>
                <button onclick="goToPage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>上一页</button>
            `;

            // 计算显示的页码范围
            let startPage = Math.max(1, currentPage - 2);
            let endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                html += `<button class="${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">${i}</button>`;
            }

            html += `
                <button onclick="goToPage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>下一页</button>
                <button onclick="goToPage(${totalPages})" ${currentPage === totalPages ? 'disabled' : ''}>尾页</button>
            `;

            pagination.innerHTML = html;
        }

        // 跳转到指定页
        function goToPage(page) {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            if (page < 1 || page > totalPages || page === currentPage) {
                return;
            }
            currentPage = page;
            loadData();
        }

        // 查询
        function search() {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            currentPage = 1;
            loadData();
        }

        // 重置查询
        function resetSearch() {
            document.getElementById('searchName').value = '';
            document.getElementById('searchCategory').value = '';
            currentPage = 1;
            loadData();
        }

        // 显示新增模态框
        function showAddModal() {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            isEditMode = false;
            document.getElementById('modalTitle').textContent = '新增选项';
            document.getElementById('optionForm').reset();
            document.getElementById('optionId').value = '';
            document.getElementById('optionModal').classList.add('show');
        }

        // 显示编辑模态框
        function showEditModal(id) {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            isEditMode = true;
            document.getElementById('modalTitle').textContent = '编辑选项';
            
            fetch(`../option/detail?id=${id}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        const option = result.data;
                        document.getElementById('optionId').value = option.id;
                        document.getElementById('name').value = option.name;
                        document.getElementById('category').value = option.category;
                        document.getElementById('value').value = option.value;
                        document.getElementById('remark').value = option.remark || '';
                        document.getElementById('optionModal').classList.add('show');
                    } else {
                        alert('获取选项详情失败：' + result.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('系统错误，请稍后重试');
                });
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('optionModal').classList.remove('show');
        }

        // 保存选项
        function saveOption() {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            const id = document.getElementById('optionId').value;
            const name = document.getElementById('name').value.trim();
            const category = document.getElementById('category').value.trim();
            const value = document.getElementById('value').value.trim();
            const remark = document.getElementById('remark').value.trim();

            // 表单验证
            if (!name) {
                alert('请输入名称');
                return;
            }
            if (!category) {
                alert('请输入范畴');
                return;
            }
            if (!value) {
                alert('请输入值');
                return;
            }

            const url = isEditMode ? '../option/update' : '../option/add';
            const params = new URLSearchParams({
                name: name,
                category: category,
                value: value,
                remark: remark
            });

            if (isEditMode) {
                params.append('id', id);
            }

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert(isEditMode ? '更新成功' : '新增成功');
                    closeModal();
                    loadData();
                } else {
                    alert('操作失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('系统错误，请稍后重试');
            });
        }

        // 删除选项
        function deleteOption(id) {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            if (!confirm('确定要删除这条选项吗？')) {
                return;
            }

            fetch('../option/delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `id=${id}`
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert('删除成功');
                    loadData();
                } else {
                    alert('删除失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('系统错误，请稍后重试');
            });
        }

        // 批量删除
        function deleteBatch() {
            // 检查登录状态
            if (!checkLogin()) {
                return;
            }
            
            const checkboxes = document.querySelectorAll('.row-check:checked');
            if (checkboxes.length === 0) {
                alert('请选择要删除的选项');
                return;
            }

            if (!confirm(`确定要删除选中的 ${checkboxes.length} 条选项吗？`)) {
                return;
            }

            const ids = Array.from(checkboxes).map(cb => cb.value).join(',');

            fetch('../option/deleteBatch', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `ids=${ids}`
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    alert('批量删除成功');
                    loadData();
                } else {
                    alert('批量删除失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('系统错误，请稍后重试');
            });
        }

        // 全选/取消全选
        function toggleCheckAll() {
            const checkAll = document.getElementById('checkAll');
            const checkboxes = document.querySelectorAll('.row-check');
            checkboxes.forEach(cb => cb.checked = checkAll.checked);
        }

        // HTML转义
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                // 清除sessionStorage中的用户名
                sessionStorage.removeItem('username');
                // 跳转到登出接口
                window.location.href = '../logout';
            }
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('optionModal');
            if (event.target === modal) {
                closeModal();
            }
        };
    </script>
</body>
</html>
